package com.gitee.chili.leisure.server;

import com.gitee.chili.leisure.RoomManager;
import com.gitee.chili.leisure.core.MessageReceiver;
import com.gitee.chili.leisure.core.Packet;
import com.gitee.chili.leisure.core.ReceiverType;
import com.gitee.chili.leisure.game.Player;
import com.gitee.chili.leisure.util.AuxiliaryRoom;
import com.gitee.chili.leisure.util.Connection;
import com.gitee.chili.leisure.util.Utils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * MessageHandlerBeforeHandler
 *
 * @author week solider
 * @since 2020.08.31
 */
@Slf4j
public class BinaryMessageHandler extends SimpleChannelInboundHandler<Packet> {

    /**
     * 消息接受者
     */
    private final MessageReceiver messageReceiver = ReceiverType.NETTY_SERVER_RECEIVER.getReceiver();

//    public BinaryMessageHandler(MessageReceiver messageReceiver) {
//        this.messageReceiver = messageReceiver;
//    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Connection.broadcaster().add(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Packet msg) {
        log.info("接收到消息 命令: [ {} ]", msg.getCmd());
        messageReceiver.onReceive(msg, ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);

        Long roomNum = Utils.asLong(ctx.channel().attr(AttributeKey.valueOf("roomNum")).get());
        Long userId = Utils.asLong(ctx.channel().attr(AttributeKey.valueOf("userId")).get());

        Optional<? extends Player> optional = RoomManager.obtain(roomNum).getPlayers()
                .stream().filter(user -> user.getUserId().equals(userId)).findFirst();

        if (optional.isPresent()) {
            // 离线
            optional.get().setOnline(Boolean.FALSE);
        } else {
            log.info("缓存丢失, channel name: [ {} ] , id: [ {} ]", ctx.name(), ctx.channel().id());
        }

        // 通知客户端玩家离线
        Connection.broadcaster().notify(roomNum, AuxiliaryRoom.off());
    }
}
